import {ModelType} from "@typegoose/typegoose/lib/types";
import {getModelForClass, modelOptions, prop} from "@typegoose/typegoose";
// @ts-ignore
import bcrypt from 'bcryptjs';

@modelOptions({ schemaOptions: { timestamps: true } })
export class User   {
    @prop({ required: true })
    username!: string;

    @prop({ required: true, unique: true })
    email!: string;

    @prop({ required: true, select: false })
    hashedPassword!: string;

    @prop({ required: true, select: false })
    salt!: string;

    static async comparePassword(this: ModelType<User> & typeof User, email: string, password: string): Promise<boolean> {
        const user = await this.findOne({ email }).select('+hashedPassword +salt');
        if (!user) {
            return false;
        }
        const hashedPassword = await bcrypt.hash(password, user.salt);
        return user.hashedPassword === hashedPassword;
    }
}

export const UserModel = getModelForClass(User);
